// index.js
Page({
  data: {
    hasChecked: false,
    checkList: []
  },
  
  onLoad() {
    this.loadCheckHistory();
  },
  
  // 加载打卡记录
  loadCheckHistory() {
    wx.cloud.callFunction({
      name: 'checkHistory',
      success: res => {
        if (res.result.success) {
          this.setData({ checkList: res.result.data })
          this.checkTodayStatus();
        } else {
          wx.showToast({ title: '加载失败', icon: 'none' })
        }
      }
    })
  },
  
  // 检查今日打卡状态
  checkTodayStatus() {
    const today = this.getUTCDateString();
    const hasChecked = this.data.checkList.some(
      item => item.date == today
    );
    this.setData({ hasChecked });
  },
  
  // 获取UTC日期字符串
  getUTCDateString() {
    const date = new Date();
    return `${date.getUTCFullYear()}/${date.getUTCMonth()+1}/${date.getUTCDate()}`;
  },
  
  // 处理打卡事件
  handleCheckIn() {
    wx.cloud.callFunction({
      name: 'checkIn',
      success: res => {
        if (res.result.success) {
          this.updateCheckData(res.result.time);
        } else {
          wx.showToast({ title: res.result.msg, icon: 'none' });
        }
      }
    });
  },
  
  // 更新打卡数据
  updateCheckData(time) {
    const today = this.getUTCDateString();
    const newRecord = { date: today, time };
    const updatedList = [newRecord, ...this.data.checkList];
    
    wx.setStorageSync('checkHistory', updatedList);
    this.setData({
      hasChecked: true,
      checkList: updatedList
    });
    wx.showToast({ title: '打卡成功', icon: 'success' });
  }
})